package net.biancheng.common.utils;

import net.biancheng.common.constant.HttpStatus;
import net.biancheng.exception.ServiceException;
import net.biancheng.common.model.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author: lb
 * @date: 2023/8/3 15:22
 * @desc: 安全服务工具类
 **/
public class SecurityUtils {


    /**
     * 获取用户ID
     * @return
     */
    public static Long getUserId(){
        try {
            return getLoginUser().getUserId();
        }catch (Exception e){
            throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户ID字符串
     * @return
     */
    public static String getUserIdStr(){
        try {
            return getLoginUser().getUserId()+"";
        }catch (Exception e){
            throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户账户
     * @return
     */
    public static String getUsername(){
        try {
            return getLoginUser().getUsername();
        }catch (Exception e){
            throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户信息
     * @return
     */
    public static LoginUser getLoginUser(){
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        }catch (Exception e){
            throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication(){
        return SecurityContextHolder.getContext().getAuthentication();
    }


    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 是否为管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId)
    {
        return userId != null && 1L == userId;
    }

}
